import React, { memo, useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useTime } from './hooks';
import { getTolk } from './api';
import { formatDate } from '../../utils';

import './index.css';

export default memo(function Home() {
  const offworkTimeStr = useTime()
  
  const [Tolk, setTolk] = useState();
  const getTolkFn = () => { getTolk().then(res => setTolk(res.data)) };
  useEffect(() => { getTolkFn() }, [])
  
  const [OpenWork, setOpenWork] = useState(true);
  const workTip = useSelector(state => state.workTip);
  useEffect(() => { setOpenWork(workTip) }, [workTip]);

  useEffect(() => {
    let timer1 = setInterval(() => {
      getTolkFn();
    }, 15000);
    return () => {
      clearInterval(timer1);
    };
  }, []);

  const [dateNow, setDateNow] = useState(Date.now)
  useEffect(() => {
    let timer2 = setInterval(() => {
      const date = Date.now
      setDateNow(date);
    }, 1000);
    return () => {
      clearInterval(timer2);
    };
  }, [])

  return (
    <div className='box-wrap'>
      <div className='timeD flex-c'>{formatDate(dateNow, 'hh:mm:ss')}</div>
      <div className='tolk flex-c'>
        <div className='flex-j'>
          <span
            className='tolkTetx text-wrap-v2'
            onClick={getTolkFn}
          >
            {Tolk?.hitokoto}
          </span>
          <span className='from_name'>
            {Tolk?.from_who?`—${Tolk?.from_who}`:null}
          </span>
        </div>
      </div>
      <div className='flex-c weatherTetx'>
        <iframe
          title='iframe'
          width='350'
          height='25'
          frameBorder='0'
          scrolling='no'
          hspace='0'
          src='https://i.tianqi.com/?c=code&id=40'
        ></iframe>
      </div>
      {OpenWork ? (<div className='flex-c'>{offworkTimeStr}</div>) : null}
    </div>
  );
});
